<?php
declare (strict_types=1);

namespace app\course\logic\live\admin;

use app\admin\logic\system\Config as SystemConfig;
use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\common\library\Queue;
use app\course\model\live\admin\LiveSmall as LiveModel;
use app\course\model\live\admin\LiveSmallSection as LiveSectionModel;
use app\course\model\live\CourseSectionLive as LiveData;

/**
 * 直播后台管理逻辑层
 */
class LiveSmallSection extends LiveSectionModel
{

    /**
     * 课时列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param    [type]                         $id  [description]
     * @param integer $pid [description]
     * @return   [type]                              [description]
     */
    public function sectionTree($id, $pid = 0)
    {
        $section_level = app(LiveModel::class)->where('id', $id)->value('section_level');
        $sectionTree   = $this->where(['course_id' => $id, 'pid' => $pid])->order(['best_sort' => 'ASC', 'id' => 'ASC'])->select();
        if ($sectionTree) {
            $time = time();
            foreach ($sectionTree as $sec) {
                $sec->hasChildren     = $this->hasChildren($sec->id);
                $sec->video_sec_level = $section_level;
                if ($sec->is_last) {
                    $sec->time        = date('Y-m-d H:i', $sec->start_time) . ' - ' . date('Y-m-d H:i', $sec->end_time);
                    $sec->simple_time = date('Y-m-d H:i', intval($sec->start_time)) . ' - ' . date('H:i', intval($sec->end_time));
                    if ($sec->start_time <= $time && $time <= $sec->end_time) {
                        $sec->live = 1;
                    } else if ($sec->start_time > $time) {
                        $sec->live = 0;
                    } else {
                        $sec->live = 2;
                    }
                }
            }
        }

        return $sectionTree;
    }

    /**
     * 是否有子集
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-24
     */
    public function hasChildren(int $pid = 0): bool
    {
        return $this->where('pid', $pid)->find() ? true : false;
    }

    /**
     * 创建课程课时
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-27
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $pid  [description]
     * @param    [type]                         $data [description]
     */
    public function addSection($id, $pid, $data)
    {
        // 检测直播配置并获取直播服务商ID
        $data['live_provider'] = $this->checkLiveProvider();
        $is_last               = $this->isLastSction($id, $pid);
        $save                  = [
            'course_id'     => $id,
            'pid'           => $pid,
            'level'         => $this->getLevel($pid),
            'is_last'       => $is_last,
            'title'         => $data['title'],
            // 'price'      => $is_last ? $data['price'] : 0,
            'audition'      => 0,
            'class_hour'    => $data['class_hour'] ?? 0,
            // 'course_ids'    => count($data['course_ids']) ? ',' . implode(',', $data['course_ids']) . ',' : '',
            'live_provider' => $data['live_provider']
        ];

        if ($is_last) {
            if (!isset($data['time']) || in_array('', $data['time']['time_slot'])) {
                throw new LogicException("请选择开播时间");

            }
            $save['start_time'] = strtotime($data['time']['date'] . ' ' . $data['time']['time_slot'][0]);
            $save['end_time']   = strtotime($data['time']['date'] . ' ' . $data['time']['time_slot'][1]);
        }

        // 验证数据
        $this->getValidate()->failException()->check($save);

        $success = $this::create($save);

        if ($success->isEmpty()) {
            throw new LogicException("新建课时失败");
        } else {
            // 队列处理，新增课时通知用户
            Queue::push('CourseNotify', [
                'type'   => 2,
                'source' => $id
            ], 30);
        }
        $course_title = app(\app\course\model\live\admin\LiveSmall::class)->where('id', $id)->value('title');

        Log::write('新建小班课课时【' . $course_title . ' - ' . $save['title'] . '】', 'live_small', 'create', true);

        return $this;
    }

    /**
     * 编辑课时
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-27
     *
     * @param    [type]                         $section [description]
     * @param    [type]                         $data    [description]
     * @return   [type]                                  [description]
     */
    public function editSection($section, $data)
    {
        // 验证数据
        $this->getValidate()->failException()->check($data);

        $section->title = $data['title'];
        // $section->price    = $data['price'];
        $section->audition = $data['audition'];

        $is_last = $section->getAttr('is_last') == 1;

        if ($is_last) {
            // 开播信息
            $live_data = app(LiveData::class)->where('room_no', $section->id)->findOrEmpty();

            $time   = time();
            $is_end = $section->end_time < $time || (!$live_data->isEmpty() && $live_data->close_time < $time);
            // 非CC云课堂直播回放
            if ($is_end && $section->live_provider != 3) {
                // 回放视频
                $playback_id = $data['playback_id'] ?? 0;

                if ($playback_id) {
                    if ($live_data->isEmpty()) {
                        $re = LiveData::create([
                            'room_no'     => $section->id,
                            'attach_id'   => $playback_id,
                            'course_id'   => $section->course_id,
                            'create_time' => $time,
                            'close_time'  => $time
                        ]);
                        if ($re->isEmpty()) {
                            throw new LogicException("编辑失败");
                        }
                    } else {
                        $live_data->attach_id = $playback_id;
                        if (!$live_data->save()) {
                            throw new LogicException("编辑失败");
                        }
                    }
                }
            } else if ($is_end && $section->live_provider == 3) {
                // CC云课堂小班课回放

                // 回放视频
                $cc_replay_url = $data['cc_replay_url'] ?? 0;

                if ($cc_replay_url) {
                    if ($live_data->isEmpty()) {
                        $re = LiveData::create([
                            'room_no'       => $section->id,
                            'cc_replay_url' => $cc_replay_url,
                            'course_id'     => $section->course_id,
                            'create_time'   => $time,
                            'close_time'    => $time
                        ]);
                        if ($re->isEmpty()) {
                            throw new LogicException("编辑失败");
                        }
                    } else {
                        $live_data->cc_replay_url = $cc_replay_url;
                        if (!$live_data->save()) {
                            throw new LogicException("编辑失败");
                        }
                    }
                }
            } else {

                if (!isset($data['time']) || in_array('', $data['time']['time_slot'])) {
                    throw new LogicException("请选择开播时间");

                }
                $data['start_time'] = $data['time']['date'] . ' ' . $data['time']['time_slot'][0];
                $data['end_time']   = $data['time']['date'] . ' ' . $data['time']['time_slot'][1];

                $section->start_time            = strtotime($data['start_time']);
                $section->end_time              = strtotime($data['end_time']);
                // $section->material_id           = $data['material_id'] ?? 0;
                $section->completion_conditions = $data['completion_conditions'] ?? 0;
                $section->class_hour            = $data['class_hour'] ?? 0;
                // $section->course_ids            = count($data['course_ids']) ? ',' . implode(',', $data['course_ids']) . ',' : '';
            }
        }
        $section->save();

        $course_title = app(\app\course\model\live\admin\LiveSmall::class)->where('id', $section->course_id)->value('title');

        Log::write('编辑小班课课时【' . $course_title . ' - ' . $section->title . '】', 'live_small', 'update', true);

        return $section;
    }

    /**
     * [isLastSction description]
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-27
     *
     * @param    [type]                         $id  [description]
     * @param    [type]                         $pid [description]
     * @return   int                             [description]
     */
    public function isLastSction($id, $pid)
    {
        $level         = $this->getLevel($pid);
        $section_level = app(LiveModel::class)->where('id', $id)->value('section_level');

        return $section_level == $level ? 1 : 0;
    }

    /**
     * 获取层级
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param    [type]                         $pid [description]
     * @return   [type]                              [description]
     */
    public function getLevel($pid = 0)
    {
        $plevel = 0;
        $pid && $plevel = $this->where('id', $pid)->value('level');
        $level = $plevel + 1;

        return $level;
    }

    /**
     * 删除
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-14
     *
     * @param int $id [description]
     * @return   [type]                             [description]
     */
    public function sectionDelete(int $id)
    {
        if ($this->hasChildren($id)) {
            throw new LogicException('存在下级，不能删除');
        }

        $section = $this->where('id', $id)->findOrFail();

        if (!$section->delete()) {
            throw new LogicException('删除失败');

        }

        $course_title = app(\app\course\model\live\admin\LiveSmall::class)->where('id', $section->course_id)->value('title');

        Log::write('删除小班课课时【' . $course_title . ' - ' . $section->title . '】', 'live_small', 'delete', true);

    }

    /**
     * 检测直播服务商
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/15
     *
     * @return int
     */
    protected function checkLiveProvider()
    {
        $config = SystemConfig::get('live_provider_used', ['provider_id' => 0]);

        $liveProviderId = intval($config['provider_id']);

        if ($liveProviderId === 0) {
            throw new LogicException('请先配置直播服务商信息并启用');
        }

        return $liveProviderId;
    }

    /**
     * 编辑指定字段
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function updateSort($id, $value)
    {
        // 信息
        $section = $this->findOrFail($id);

        $section->best_sort = $value;

        if (!$section->force()->save()) {
            throw new LogicException("更新失败");
        }

        // 返回值
        return $section;
    }
}
